package com.qianfeng.dbsm.impl;

import com.qianfeng.dbsm.admin.service.TbMemberService;
import com.qianfeng.dbsm.common.Contants;
import com.qianfeng.dbsm.common.PageInfo;
import com.qianfeng.dbsm.dao.TbOrderDao;
import com.qianfeng.dbsm.dao.TbOrderDetailDao;
import com.qianfeng.dbsm.entity.TbOrder;
import com.qianfeng.dbsm.entity.TbOrderDetail;
import com.qianfeng.dbsm.service.TbOrderCommissionService;
import com.qianfeng.dbsm.service.TbOrderService;
import com.qianfeng.dbsm.vo.GenerateOrderVo;
import com.qianfeng.dbsm.vo.OrderQueryParamVo;
import com.qianfeng.dbsm.vo.OrderVo;
import com.qianfeng.dbsm.vo.PayDetailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * (TbOrder)表服务实现类
 *
 * @author Chance
 * @since 2022-11-14 14:34:04
 */
@Transactional
@Service("orderService")
public class TbOrderServiceImpl implements TbOrderService {
    @Autowired
    private TbOrderDao tbOrderDao;

    @Autowired
    private TbOrderDetailDao tbOrderDetailDao;

    @Autowired
    private TbOrderCommissionService tbOrderCommissionService;

    /**
     * 创建订单 返回生成的订单编号
     * @param cardIds
     * @return
     */
    public String generateOrderByCart(String cardIds) {

        if(cardIds!=null && !"".equals(cardIds)){
            String[] cardIdArr = cardIds.split(",");
            //遍历购物车id
            //todo 通过购物车id拿到购物车info信息 然后再遍历购物车 清单 生成订单信息
            List<Object> cardInfoList = new ArrayList();
            //订单编号
            String orderNumber = this.generateOrderNumber();
            //创建订单基本信息
            TbOrder order = new TbOrder();
            order.setOrderNumber(orderNumber);
            order.setOrderNumber("");//从购物车表拿
            //订单状态
            order.setOrderState(Contants.OrderStatusCode.CREATED_NOT_PAID.getCode());//创建订单未支付
            //订单创建时间
            order.setOrderTime(new Date());
            cardInfoList.forEach(o->{
                //构造订单详情数据
                TbOrderDetail orderDetail = new TbOrderDetail();
                orderDetail.setOrderNumber(orderNumber);
                orderDetail.setNum(0);//从购物车表来
                orderDetail.setOnePrice(0.0);//从购物车表来
                orderDetail.setSumPrice(0.0);//从购物车表来
                orderDetail.setAttrItem("");//从购物车表来
                tbOrderDetailDao.insert(orderDetail);
            });
            tbOrderDao.insert(order);
            return orderNumber;
        }
        throw new RuntimeException("生成订单异常,购物车编号不能为空");
    }

    /**
     * 用户直接点击 立即购买 所走的方法
     * @param generateOrderVo
     * @return
     */
    @Override
    public String generateOrderByNoCart(GenerateOrderVo generateOrderVo) {
        //订单编号
        String orderNumber = this.generateOrderNumber();
        try {
            //创建订单基本信息
            TbOrder order = new TbOrder();
            order.setOrderNumber(orderNumber);
            order.setOrderState(Contants.OrderStatusCode.CREATED_NOT_PAID.getCode());//创建订单未支付
            order.setAddressId(generateOrderVo.getAddressId());
            order.setMemberId(Integer.valueOf(generateOrderVo.getMemberId()));
            order.setOrderTime(new Date());
            order.setSellerId(Integer.valueOf(generateOrderVo.getSellerId()));
            order.setPayPrice(Double.valueOf(generateOrderVo.getOnePrice())*Double.valueOf(generateOrderVo.getNum()));
            //订单状态
            order.setOrderState(Contants.OrderStatusCode.CREATED_NOT_PAID.getCode());//创建订单未支付
            //订单创建时间
            order.setOrderTime(new Date());
            ///接下来封装orderDetail对象
            TbOrderDetail detail = new TbOrderDetail();
            detail.setAttrItem(generateOrderVo.getAttribute());
            detail.setNum(Integer.valueOf(generateOrderVo.getNum()));
            detail.setProductId(generateOrderVo.getProductId());
            detail.setOnePrice(Double.valueOf(generateOrderVo.getOnePrice()));
            detail.setSumPrice(detail.getOnePrice()*detail.getNum());
            detail.setOrderNumber(orderNumber);
            //todo 这里调用 product那边的接口 更改库存
            tbOrderDao.insert(order);
            tbOrderDetailDao.insert(detail);
        }catch (Exception e){
            throw new RuntimeException("创建订单失败！请重试");
        }
        return orderNumber;
    }

    /**
     * 创建订单流水号的方法
     * @return
     */
    public String generateOrderNumber(){
        StringBuffer sb = new StringBuffer();
        sb.append("order");
        //获取当前时间
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        //获取当前时间的字符串
        String nowDate =  simpleDateFormat.format(date);
        sb.append(nowDate);
        //流水号，获取最新的订单流水号进行判断
        String latestOrderNumber = tbOrderDao.findLatestOrderNumber();
        //如果没有订单，那么就从00001开始
        if(latestOrderNumber == null){
            sb.append(Contants.ORDERPRESTR);
        }else{
            //最新的流水号和nowDate是同一天，那么则流水增加
            String latestOrderDate = latestOrderNumber.substring(5,13);//截取时间
            if(nowDate.equals(latestOrderDate)){
                //获取流水
                String no = latestOrderNumber.substring(13,latestOrderNumber.length());//截取时间
                //转换成int,并且通过format进行补0
                sb.append(String.format("%05d",Integer.parseInt(no)+1));
            }else{
                //如果最新的流水号和nowDate不是同一天，那么流水从00001开始
                sb.append(Contants.ORDERPRESTR);
            }
        }
        return sb.toString();
    }

    /**
     * 查询当前用户下所有订单信息 不传分页信息默认查询第一页前10条
     * @param memberId 会员编号
     * @return
     */
    public List<OrderVo> queryOrderInfoByMemberId(String memberId,String orderState,String page,String pageSize) {
        PageInfo pageInfo = new PageInfo();
        if(page!=null && !"".equals(page)){
            pageInfo.setPage(Integer.valueOf(page));
        }
        if(pageSize != null && !"".equals(pageSize)){
            pageInfo.setPageSize(Integer.valueOf(pageSize));
        }
        Integer orderStatus = null;
        if(orderState != null && !"".equals(orderState)){
            orderStatus = Integer.valueOf(orderState);
        }
        return tbOrderDao.queryOrderInfoByMemberId(memberId,orderStatus, (pageInfo.getPage()-1)* pageInfo.getPageSize(), pageInfo.getPageSize());
    }

    /**
     * @param orderNumber 修改订单状态为
     * @return
     */
    public int updateOrderInfo(String orderNumber,Integer orderState) {
        TbOrder tbOrder = tbOrderDao.queryByOrderNumber(orderNumber);
        tbOrder.setPayTime(new Date());
        tbOrder.setOrderState(orderState);
        //订单状态
        int line = tbOrderDao.update(tbOrder);
        return line;
    }

    /**
     * 条件查询订单列表（用于后台订单管理）
     * @param queryParamVo
     * @return
     */
    public List<OrderVo> queryOrderInfoByParam(OrderQueryParamVo queryParamVo){
        PageInfo pageInfo = new PageInfo();
        //处理分页参数为空 的情况
        if(queryParamVo.getPage() == null || "".equals(queryParamVo.getPage())){
            queryParamVo.setPage(pageInfo.getPage());
        }
        if(queryParamVo.getPageSize() == null || "".equals(queryParamVo.getPageSize())){
            queryParamVo.setPageSize(pageInfo.getPageSize());
        }
        queryParamVo.setPage((queryParamVo.getPage()-1)* queryParamVo.getPageSize());
        List<OrderVo> orderVos = tbOrderDao.queryOrderInfoByParam(queryParamVo);
        return orderVos;
    }

    /**
     * 用户点击确认收货操作 完成订单
     * @param orderNumber
     * @return
     */
    @Override
    public boolean confirmOrderCompleted(String orderNumber) {

        //判断当前订单编号是否已经完成
        List<OrderVo> orderVoList = tbOrderDao.queryOrderInfoByOrderNumber(orderNumber);
        if(orderVoList == null || orderVoList.size() == 0){
            throw new RuntimeException("当前订单不存在,不可执行当前操作!!!");
        }
        OrderVo orderVo = orderVoList.get(0);
        if(orderVo.getOrderState() == Contants.OrderStatusCode.DELIVERED_NOT_RECEIVE.getCode()){//只有订单状态为4：已发货未签收 才可确认收货
            //开始执行订单完成操作
            //在这里执行创建分润信息
            tbOrderCommissionService.createCommissionData(orderVo);
            //5.最后修改订单状态
            TbOrder order = tbOrderDao.queryByOrderNumber(orderNumber);
            order.setOrderState(Contants.OrderStatusCode.RECEIVED_NO_COMMENT.getCode());//订单变成 已签收 未评价
            tbOrderDao.update(order);
        }else{
            throw new RuntimeException("当前订单状态不可执行确认收货操作");
        }
        return true;
    }

    /**
     * 通过订单编号查询订单信息
     * @param orderNumber
     * @return
     */
    @Override
    public TbOrder queryByOrderNumber(String orderNumber) {
        return tbOrderDao.queryByOrderNumber(orderNumber);
    }

    /**
     * 订单支付
     * @param orderNumber
     * @param payType
     * @return
     */
    @Override
    public boolean gotoPay(String orderNumber, String payType) {
        //填充支付方式 和支付时间
        try{
            //这里模拟支付 修改状态为已支付 方便往后走流程
            TbOrder order = queryByOrderNumber(orderNumber);
            if(order == null){
                throw new RuntimeException("当前订单不存在，无法执行该操作");
            }
            if(payType==null || "".equals(payType)){
                throw new RuntimeException("请选择正确的支付方式:1.支付宝 2.微信 3.网银 4.云闪付");
            }
            order.setPayTime(new Date());
            order.setPayment(Integer.valueOf(payType));
            order.setOrderState(Contants.OrderStatusCode.CREATED_PAID.getCode());
            this.tbOrderDao.update(order);
            return true;
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }


}
